package com.tnl.hunter.webchat.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.biz.hunter.cache.EhCacheElement;
import com.biz.hunter.cache.EhCacheFactory;
import com.biz.hunter.db.entity.jsConfig;
import com.biz.qq.wechat.api.AccessTokenAPI;
import com.biz.qq.wechat.api.JSTicketAPI;
import com.biz.qq.wechat.entity.AccessToken;
import com.biz.qq.wechat.entity.JSTicket;
import com.biz.system.config.Config;
import com.biz.system.config.WebchatServiceConstant;
import com.biz.wechat.util.SignUtil;
import com.jfinal.weixin.sdk.api.ApiConfigKit;

@Repository
public class SysConfigRepo {

	private static final Logger logger = LoggerFactory.getLogger(SysConfigRepo.class);
			
	public String getTokenKey() {
		return WebchatServiceConstant.CACHE_KEY_ACCESS_TOKEN
				+ WebchatServiceConstant.APPID;
	}

	private String getTicketKey() {
		return WebchatServiceConstant.CACHE_KEY_JSTICKET
				+ WebchatServiceConstant.APPID;
	}

	public String getAccessToken() {
		EhCacheElement cachedToken = EhCacheFactory.get(getTokenKey());
		String token;
		AccessToken accessToken = new AccessToken();
		if (cachedToken == null) {
			accessToken = AccessTokenAPI.getAccessToken(
					WebchatServiceConstant.APPID,
					WebchatServiceConstant.APPSECRET);
			EhCacheElement cacheToken = new EhCacheElement();
			token = accessToken.getAccess_token();
			cacheToken.setObj(token);
			//TODO: persistent to DB
			EhCacheFactory.add(getTokenKey(), cacheToken,
					accessToken.getExpires_in() - 200);
		} else {
			token = (String) cachedToken.getObj();
		}
		logger.info("sysconfigrepo token="+token);
		return token;
	}

	public String getJsTicket() {
		EhCacheElement cachedToken = EhCacheFactory.get(getTicketKey());
		String jsticket = null;
		String token = getAccessToken();
		JSTicket ticket = null;
		if (cachedToken == null) {
			ticket = JSTicketAPI.getJsTicket(token);
			EhCacheElement cacheToken = new EhCacheElement();
			jsticket = ticket.getTicket();
			cacheToken.setObj(jsticket);
			EhCacheFactory.add(getTicketKey(), cacheToken,
					ticket.getExpires_in() - 200);

		} else {
			jsticket = (String) cachedToken.getObj();
		}
		return jsticket;
	}

}
